﻿using System;
using System.Collections;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using AdventureWorksService.Web;
using System.ServiceModel.DomainServices.Client;


// Indirect Edit Form
namespace DemoDataGridToolBar
{
	public partial class ProductFormRIA_indir : System.Windows.Controls.DGTB.DataFormWindow
	{
		public ProductFormRIA_indir()
		{
			InitializeComponent();
			CancelButton.Click += new RoutedEventHandler(CancelButton_Click);
			OKButton.Click += new RoutedEventHandler(OKButton_Click);
			_dc = new AdventureWorksDomainContext();
		}

		private AdventureWorksDomainContext _dc;
		private Product _data;

		#region -- override --------------
		public override void SetDataContect(object item)
		{
			this.DataContext = _data;
		}

		override public bool ValidateItem()
		{
			return !coErrorSummary.HasErrors;
		}

		override public void CancelEdit()
		{
			_dc.RejectChanges();
		}

		override public object CreateNewItem()
		{
			_data = new Product();
			_data.ProductID = Guid.NewGuid();
			_data.SellStartDate = DateTime.Now.Date;

			var data = new vwProduct();
			return data;
		}

		//public override void AddItem(Action<bool> callback)
		//{
		//  _dc.RejectChanges();
		//  callback(true);
			
		//}

		public override void EditItem(object item, Action<bool> callback)
		{
			_dc.RejectChanges();
			//--
			vwProduct viewItem = item as vwProduct;
			// načtu data z DB
			var qq = _dc.GetProductQuery().Where(n => n.ProductID == viewItem.ProductID);
			_dc.Load<Product>(qq, LoadBehavior.RefreshCurrent, (p) => {
				// Assync Result
				bool ok = !(p.IsCanceled || p.HasError);
				if(ok) {
					_data = p.Entities.First();
				} else {
					//todo:Error
				}
				BusyCnt--;
				//base.EditItem(item);

				callback(ok);
			}, null);
			BusyCnt++;
		}

		public override void SubmitChanges(bool isNewItem, Action<bool> callback)
		{
			if(isNewItem)_dc.Products.Add(_data); 
			_dc.SubmitChanges((a) => {
				bool ok = !(a.IsCanceled || a.HasError);
				if(ok) {
					var data = CurrentItem as vwProduct;
					data.ProductID = _data.ProductID;
					data.Color = _data.Color;
					data.Name = _data.Name;
					if(isNewItem) ((DomainDataSourceView)ItemsSource).Add(data);
				}
				BusyCnt--;
				callback(ok);
			}, null);
			BusyCnt++;
		}

		#endregion

		void OKButton_Click(object sender, RoutedEventArgs e)
		{
			CommitEditAndCloseWindow();
		}

		void CancelButton_Click(object sender, RoutedEventArgs e)
		{
			CancelEditAndCloseWindow();
		}

	}
}
